package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 上传保存视频
     *
     * @param video
     * @return
     */
    @Override
    public String sava(Video video) {
        //设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        //保存数据
        mongoTemplate.save(video);
        //返回自动生成的id
        return video.getId().toHexString();
    }

    /**
     * 根据vid查询数据
     *
     * @param vids
     * @return
     */
    @Override
    public List<Video> queryVideoList(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query, Video.class);
    }

    /**
     * 分页查询视频数据
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> pr(int page, Integer pagesize) {
        Query query = new Query().skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }

    /**
     * 查询视频列表
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    @Override
    public PageResult videos(Integer page, Integer pagesize, Long uid) {
        Query query = new Query();
        //1.构建条件查询id相等的
        query.addCriteria(Criteria.where("userId").is(uid));
        //2.得出数量
        long count = mongoTemplate.count(query, Video.class);
        //3.进行分页和排序
        query.skip((page - 1) * pagesize)
                .limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        //4.获取视频列表集合
        List<Video> list = mongoTemplate.find(query, Video.class);
        //5.返回
        return new PageResult(page, pagesize, count, list);
    }
}
